package ren.nearby.http.utils.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

/**
 * Created by Administrator on 2016/7/26.
 */
public class NumberUtils {
    /**
     * 保留一位小数
     *
     * @param number
     * @return
     */
    public static String formatOneDecimal(float number) {
        DecimalFormat oneDec = new DecimalFormat("##0.0");
        return oneDec.format(number);
    }

    /**
     * 保留两位小数
     *
     * @param number
     * @return
     */
    public static String formatTwoDecimal(float number) {

        DecimalFormat twoDec = new DecimalFormat("##0.00");
        return twoDec.format(number);
    }

    /**
     * 保留两位小数百分比
     *
     * @param number
     * @return
     */
    public static String formatTwoDecimalPercent(float number) {
        return formatTwoDecimal(number) + "%";
    }

    /**
     * 元成万元
     * @param number
     * @return
     */
    public static String formatThousand(float number) {

        // 具体的注册资本等信息（单位元）
        BigDecimal bigDecimal = new BigDecimal(number);
        // 转换为万元（除以10000）
        BigDecimal decimal = bigDecimal.divide(new BigDecimal("10000"));
        // 保留两位小数
        DecimalFormat formater = new DecimalFormat("0.00");
        // 四舍五入
        formater.setRoundingMode(RoundingMode.HALF_UP);    // 5000008.89
//        formater.setRoundingMode(RoundingMode.HALF_DOWN);// 5000008.89
//        formater.setRoundingMode(RoundingMode.HALF_EVEN);

        // 格式化完成之后得出结果
        String formatNum = formater.format(decimal);

        return formatNum;
    }


    /**
     * 四舍五入 Double
     *
     * @param number
     * @param scale  scale of the result returned.
     * @return
     */
    public static double roundingNumberDouble(float number, int scale) {
        return roundingNumberDouble(number, scale, RoundingMode.HALF_UP);
    }

    /**
     * 四舍五入 Float
     *
     * @param number
     * @param scale
     * @return
     */
    public static float roundingNumberFloat(float number, int scale) {
        return roundingNumberFloat(number, scale, RoundingMode.HALF_UP);
    }

    /**
     * 四舍五入 Double
     *
     * @param number
     * @param scale        scale of the result returned.
     * @param roundingMode rounding mode to be used to round the result.
     * @return
     */
    public static double roundingNumberDouble(float number, int scale, RoundingMode roundingMode) {
        BigDecimal b = new BigDecimal(number);
        return b.setScale(scale, roundingMode).doubleValue();
    }

    /**
     * 四舍五入 Float
     *
     * @param number
     * @param scale
     * @param roundingMode
     * @return
     */
    public static float roundingNumberFloat(float number, int scale, RoundingMode roundingMode) {
        BigDecimal b = new BigDecimal(number);
        return b.setScale(scale, roundingMode).floatValue();
    }
}
